# Copyright 2021 Wechat Group, Tencent
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import ir.node
from backend.cppcode.nodegenerator.nodegenerator import NodeGenerator
from backend.cppcode.common import get_cpp_constant_value


class CreateVector(NodeGenerator):
    @classmethod
    def accept(cls, node: ir.node.Node):
        return isinstance(node, ir.node.base.CreateVector)

    @property
    def code(self):
        code = "std::vector<{outputs[0].dtype}> {outputs[0]};\n".format(**self.fmt_dict)
        for v in self.node.vec:
            if isinstance(v, list):
                for rv in v:
                    code += "    {outputs[0]}.push_back(static_cast<{outputs[0].dtype}>({value}));\n".format(
                        value=rv, **self.fmt_dict
                    )
            elif isinstance(v, int):
                if self.inputs[v].is_value():
                    code += "    {outputs[0]}.push_back(static_cast<{outputs[0].dtype}>({value}));\n".format(
                        value=self.fmt_dict["inputs"][v], **self.fmt_dict
                    )
                elif self.inputs[v].is_vector():
                    code += "    for (auto s_tmp : {value})\n".format(
                        value=self.fmt_dict["inputs"][v]
                    )
                    code += "    {\n"
                    code += "        {outputs[0]}.push_back(s_tmp);\n".format(
                        **self.fmt_dict
                    )
                    code += "    }\n"
            else:
                raise RuntimeError("Unknow error")
        return code
